<template>
  <div class="body-layout" style="width: 100%">
    <header class="top-header">
      <!-- 返回按钮 -->
      <a @click="goBack" class="header-left"></a>
      <article class="header-middle">观点详情</article>
    </header>
    <!-- 详情 -->
    <div class="vf-detail marginTop44">
      <div class="vf-detail_container">
        <!-- 头部内容 -->
        <div class="vf-detail_container__header border-bottom">
          <h1 class="title" v-if="viewDetail.view_title">{{viewDetail.view_title}}</h1>
          <div class="header-info">
            <div class="header-info_text">
							<span @click="goLargeVipDetail" v-stat='{action_type:2,button_type:7}'>
								<img src="../assets/images/icon-v.png" alt="" v-if="viewDetail.author_name">{{viewDetail.author_name}}
							</span>
              <span v-if="viewDetail.category_name">#{{viewDetail.category_name}}</span>
              <span v-if="viewDetail.publish_time">{{publishTime}}</span>
            </div>

            <div class="header-info_btn_liked" @click.stop="postFollow" v-if="isFollow">
              <a href="javascript:;">已关注</a>
            </div>
            <div class="header-info_btn" @click.stop="postFollow" v-else v-stat='{action_type:2,button_type:8}'>
              <a href="javascript:;"><i></i>关注</a>
            </div>
          </div>
        </div>
        <!-- 文章内容 -->
        <div class="vf-detail_container__main" v-html="viewDetail.view_content">
        </div>
        <!-- 点赞 -->
        <div class="vf-detail_container__good">
          <a href="javascript:;" class="good_btn" v-stat='{action_type:2,button_type:9}' @click="postLike(2)"
             :class="{'selected':isLike}">
            <svg class="icon" aria-hidden="true">
              <use xlink:href="#icon-thumbs"></use>
            </svg>
            {{likeAmount > 0 ? likeAmount : ""}}
          </a>
        </div>
      </div>
    </div>
    <!-- 大V关注信息 -->
    <div class="V-info" @click="goLargeVipDetail" v-stat='{action_type:2,button_type:10}'>
      <div class="V-info_content">
        <div class="V-pic">
          <img :src="author.author_avatar" alt="">
        </div>
        <div class="V-info">
          <div class="header-info">
            <div class="header-info_text">
							<span>
								<img src="../assets/images/icon-v.png" alt="">{{author.author_name}}
							</span>
            </div>
            <div class="header-info_btn_liked" @click.stop="postFollow" v-if="isFollow">
              <a href="javascript:;">已关注</a>
            </div>
            <div class="header-info_btn" @click.stop="postFollow" v-stat='{action_type:2,button_type:11}' v-else>
              <a href="javascript:;"><i></i>关注</a>
            </div>
          </div>
          <p>{{author.desc}}</p>
        </div>
      </div>
    </div>
    <div class="vf-detail" style="padding-bottom: 50px;">
      <div class="vf-detail_container">
        <!-- 其他大V观点 -->
        <div class="vf-detail_container__otherV " v-if="recommendList&&recommendList.length>0">
          <h3 class="title border-bottom">其他大V的观点</h3>
          <ul>
            <li v-for="(item, index) in recommendList" :key="index" @click="goDetail(item.view_id)"
                v-stat='{action_type:2,button_type:12}'>
              <a href="javascript:;" v-if="item.view_title">{{item.view_title}}</a>
            </li>
          </ul>
        </div>
        <!-- 评价列表 -->
        <div id="mao">
          <div class="vf-detail_container__evaulate"
               v-if="commendList&&commendList.comment_list&&commendList.comment_list.length>0">
            <h3 class="title border-bottom">评论</h3>
            <div class="evaulate-list" v-if="commendList.comment_list" v-for="(item, index) in commendList.comment_list"
                 :key="index">
              <div class="pic">
                <img v-if="item.user_avatar" :src="item.user_avatar" alt="">
              </div>
              <div class="info">
                <div class="info-content">
                  <p v-if="item.user_name">{{item.user_name}}</p>
                  <p v-if="item.content">{{item.content}}</p>
                  <div class="detail clearfix">
                    <span class="times">{{item.publish_time}}</span>
                    <span class="message" @click="showReplayInput(index)"
                          v-stat='{action_type:2,button_type:14,extra: view_id||""}'>
										<svg class="icon" aria-hidden="true">
  											<use xlink:href="#icon-message"></use>
										</svg>{{item.reply.length > 99 ? "99+" : item.reply.length + ""}}
										<i v-if="item.reply&&item.reply.length>0 || item.showReplay"></i>
									</span>
                    <span class="nums" @click="postCommentLike(item.comment_id, item.is_like)"
                          v-stat='{action_type:2,button_type:13}'>
										<svg class="icon" aria-hidden="true" :class="{'selected':item.is_like}">
  											<use xlink:href="#icon-thumbs"></use>
										</svg>{{item.like_amount > 99 ? "99+" : item.like_amount + ""}}
									</span>
                  </div>
                  <div class="return-message reply" v-show="item.showReplay">
                    <div class="return-message_list-text">
                      <div class="input-value">
                        <input type="text" maxlength="500" placeholder="评论这条，最多输入500个字。" v-model="item['userReplay']">
                      </div>
                      <div class="reply-btn" @click="postCommentReply(item.comment_id, index, item.userReplay)">
                        <span>回复</span>
                      </div>
                    </div>
                  </div>
                  <div class="return-message" v-if="item.reply&&item.reply.length>0">
                    <div class="return-message_list"
                         v-for="(relayItem,i) in item.reply" :key="i">
                      <em>{{relayItem.user_name}}：</em><em>{{relayItem.content}}</em></div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 加载更多 -->
      <article class="vf-bottom-tps">
        <div class="vf-bottom-tps_line" v-show="bottomText.length>0">
          <span>{{bottomText}}</span>
        </div>
      </article>
    </div>
    <!-- 底部 -->
    <div class="detail-footer border-top">
      <div class="detail-footer_left" @click="goComment" v-stat='{action_type:2,button_type:15,extra:view_id}'>
        有话要说...
      </div>
      <div class="detail-footer_right">
        <a onclick="javascript:document.getElementById('mao').scrollIntoView()"
           v-stat='{action_type:2,button_type:16,extra:view_id || ""}'>
          <svg class="icon" aria-hidden="true">
            <use xlink:href="#icon-message"></use>
          </svg>
          <p v-if="commendList.total_count">{{commendList.total_count > 99 ? "99+" : commendList.total_count + ""}}</p>
        </a>
        <a href="javascript:;" @click="postLike(1)" v-stat='{action_type:2,button_type:17}'>
          <svg class="icon" aria-hidden="true" :class="{'selected':isCollect}">
            <use xlink:href="#icon-star"></use>
          </svg>
        </a>
        <a href="javascript:;" @click="openShareList" v-stat='{action_type:2,button_type:18,extra:view_id}'>
          <svg class="icon" aria-hidden="true">
            <use xlink:href="#icon-share"></use>
          </svg>
        </a>
      </div>
    </div>

    <!-- 分享 -->
    <div class="mask mask-black" :style="{'display': isblock}" @click="hideShareMask"></div>
    <div class="share-tips" :style="{'display': isblock}" @click="hideShareMask">
      <img src="../assets/images/tips-img.png"/>
      <p>点击这里，将它分享到朋友圈或分享给指定好友</p>
    </div>
    <div class="mask mask-share" :style="{'display': isShareListMask}"></div>
    <div class="vf-share" :style="{'display': isShareListMask}">
      <ul v-if="shareArr">
        <li v-show="isWechat" v-for="(item, index) in shareArr" :key="index" @click="openShareMask(index)">
          <a href="javascript:;">
            <img :src="item.shareIcon" alt="">
            <p>{{item.name}}</p>
          </a>
        </li>
        <li v-show="!isWechat">
          <a :href="weiboUrl" target="_blank">
            <img :src="require('../assets/images/icon-wb.png')" alt="">
            <p>新浪微博</p>
          </a>
        </li>
        <li class="tag-read" :data-clipboard-text="url" @click="copy" v-stat='{action_type:2,button_type:24,extra:""}'>
          <a href="javascript:;">
            <img :src="require('../assets/images/icon-share.png')" alt="">
            <p>复制链接</p>
          </a>
        </li>

      </ul>
      <button type="button" class="phone-btn" @click="hideShareMaskList">取消</button>
    </div>
  </div>

</template>

<script>
  import util from '@/lib/util.js';
  import {wechatReady, isWechat, wechatConfig} from '@/lib/wechat.js';
  import Clipboard from 'clipboard';

  export default {
    name: 'Detail',
    components: {},
    data() {
      return {
        author: {},         //  作者详情
        viewDetail: {},     //  观点详情
        likeAmount: 0,      //  观点点赞数
        recommendList: [],  //  推荐列表
        commendList: {},    //  评论列表及回复
        commendTotal: 0,
        isFollow: 0,        //  0:取消关注(已关注)，1:关注(当前未关注)
        isLike: 0,    //  1 默认点赞 初始化修改
        isCollect: 0, //  1 默认收藏 初始化修改
        view_id: '',
        author_id: '',
        shareArr: [{"name": '微信好友', shareIcon: require("../assets/images/icon-wx.png")},
          {"name": '微信朋友圈', shareIcon: require("../assets/images/icon-pyq.png")},
          {"name": 'QQ空间', shareIcon: require("../assets/images/icon-qqzone.png")},
          {"name": 'QQ', shareIcon: require("../assets/images/icon-qq.png")}],
        isblock: 'none',
        isOpenShare: false,
        isShareListMask: 'none',
        url: window.location.href,
        weiboUrl: "",
        downFlag: true,//是否还有数据 true 还有数据
        sw: true,//是否正在请求数据中，防止多次请求 true 加载完毕
        last_id: 0,
        isWechat: false,
        bottomText: "",//底部提示文字
        pageSize: 3//分页的页面大小
      }
    },
    watch: {
      "$route": "initData"
    },
    computed: {
      publishTime() {
        if (typeof(this.viewDetail.publish_time) === 'number') {
          let date = new Date(this.viewDetail.publish_time);
          return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
//            + ' '+ date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();
        } else {
          return this.viewDetail.publish_time.slice(0, 10)
        }
      }
    },
    created() {

      this.initData();

    },
    mounted() {
      // 处理登录跳转到第四篇逻辑
      util.ajax.get('user/get').then((res) => {

        if (res.code == '1201' || res.code == '1202') {
          // 用户未登录状态
          if (!sessionStorage.getItem("readCount")) {
            sessionStorage.setItem("readCount", 1)
          } else {
            // 获取目前阅读篇数
            let count = sessionStorage.getItem("readCount")
            if (count == 3) {
              window.sessionStorage.setItem('routerForm', 1);
            }
            if (count < 3) {
              let countAdd = Number(count) + 1;
              sessionStorage.setItem("readCount", countAdd)
            } else {
              this.$toast('请登录', {
                duration: '1000'
              });
              this.$router.replace({name: 'Login'})
            }
          }
        } else {
          // 登录成功的话, 清掉计数
          if (res.code == 1) {
            sessionStorage.removeItem("readCount")
          }
        }
      });
      this.$nextTick(() => {
        window.addEventListener('scroll', this.onScrollPull)
      })
    },
    methods: {
      copy() {
        // 复制链接
        var clipboard = new Clipboard('.tag-read')
        clipboard.on('success', e => {
          this.$toast('复制成功', {
            duration: '1000'
          });
          // 释放内存
          clipboard.destroy()
        })
        clipboard.on('error', e => {
          // 不支持复制

          this.$toast('该浏览器不支持自动复制', {
            duration: '1000'
          });
          // 释放内存
          clipboard.destroy()
        })
      },
      resetData() {
        let rawData = {
          likeAmount: 0,      //  观点点赞数
          commendList: {},    //  评价列表及回复
          isFollow: 0,        //  0:取消关注(已关注)，1:关注(当前未关注)
          isLike: 0,    //  1 默认点赞 初始化修改
          isCollect: 0, //  1 默认收藏 初始化修改
          isblock: 'none',
          isOpenShare: false,
          isShareListMask: 'none',
          url: window.location.href,
          downFlag: true,
          sw: true,
          last_id: 0,
          bottomText: ""
        };
        for (let key in rawData) {
          this[key] = rawData[key];
        }
      },
      initData(to, from) {
        if (this.$route.path == "/pages/Detail" && (this.view_id != this.$route.query.id || this.$route.query.t)) {
          this.resetData();
          this.view_id = this.$route.query.id;
          this.fetchViewDetail();
          this.fetchStatistic();
          this.fetchRecommendList();
          this.fetchCommentList();
          this.fetchActionStatus();
        }

      },
      onScrollPull(e) {
        if (this.$el.querySelector('.vf-detail_container__evaulate')) {
          let innerHeight = this.$el.querySelector('.vf-detail_container__evaulate').clientHeight;
          let bottomHeight = this.$el.querySelector('.vf-bottom-tps');
          let scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
          if (innerHeight <= scrollTop + document.documentElement.clientHeight) {
            if (this.sw == true && this.downFlag) {
              // 将开关关闭
              this.sw = false;
              this.fetchCommentList(this.last_id);
            }
          }
        }
      },
      fetchViewDetail() {
        let pic = "http://image-test.davfang.com/saas/id/2018/07/05/71ca43a2-ead6-4595-b225-b36f60a7662d.png";
        // 获取观点详情
        util.ajax.get(`/view/detail?view_id=${this.view_id}`)
          .then((res) => {
            if (res.code == 1) {
              this.viewDetail = res.data;
              this.author_id = res.data.author_id;
              this.fatchAuthor();
              this.authFollowStatus();
              let shareImg = (this.viewDetail.img_list && this.viewDetail.img_list.length) > 0 ? this.viewDetail.img_list[0].url : pic
              this.isWechat = isWechat();
              if (this.isWechat) {
                wechatConfig(this.url);
                wx.ready(() => {
                  const config = {
                    link: this.url,
                    title: this.viewDetail.view_title,
                    desc: this.viewDetail.view_content.replace(/&nbsp;/g, '').replace(/<\/?.+?>/g, ""),
                    imgUrl: shareImg,
                    complete: (res) => {
                      setTimeout(() => {
                        this.hideShareMask();
                        this.hideShareMaskList();
                      }, 1000);
                    },
                    error: function (res) {

                      this.$toast('分享失败', {
                        duration: '1000'
                      });
                    }
                  };
                  wx.onMenuShareAppMessage(config);
                  wx.onMenuShareTimeline(config);
                  wx.onMenuShareQQ(config);
                  wx.onMenuShareWeibo(config);
                  wx.onMenuShareQZone(config);
                })
              } else {
                this.weiboUrl = "http://service.weibo.com/share/share.php?appkey=3959825831&language=zh_cn&url="
                  + encodeURIComponent(this.url) + "&pic=" + encodeURIComponent(shareImg)
                  + "&title=" + this.viewDetail.view_title;
              }
            }
          });
      },
      fatchAuthor() {
        // 获取作者详情
        util.ajax.get(`/author/detail?author_id=${this.author_id}`).then((res) => {
          if (res && res.code == 1) {
            this.author = res.data;
          }
        });
      },
      fetchStatistic() {
        // 获取观点点赞人数
        util.ajax.get(`/view/statistics/list?view_id_list=${this.view_id}`).then((res) => {
          // 模拟
          if (res) {
            this.likeAmount = res.data[0].like_amount;
          }
        });
      },
      fetchRecommendList() {
        // 获取推荐评论列表
        util.ajax.get(`/view/recommend/list?view_id=${this.view_id}`).then((res) => {
          if (res) {
            this.recommendList = res.data;
          }
        });
      },
      fetchCommentList() {
        // 获取该条观点评论列表 首次加载lastId为0
        let ori_last_id = this.last_id;
        util.ajax.get(`/comment/list?view_id=${this.view_id}&&last_id=${this.last_id}&&page_size=${this.pageSize}`).then((res) => {
          if (res.code == 1) {
            this.commendTotal = res.data.total_count;
            if (res.data.comment_list && res.data.comment_list.length > 0) {
              //调整数据格式
              res.data.comment_list = res.data.comment_list.map((item, index) => {
                item['publish_time'] = util.formatDate(item['publish_time']);
                item['user_avatar'] = item['user_avatar'] || item['user_head'];
                item['reply'] = item['reply'] || [];
                item.userReplay = '';
                item.showReplay = false;
                return item;
              });

              if (this.last_id == 0) {
                this.commendList = res.data;
              } else {
                this.commendList.comment_list = this.commendList.comment_list.concat(res.data.comment_list);
              }

              // 取最后一条数据的comment_id
              let len = res.data.comment_list.length - 1;
              this.last_id = res.data.comment_list[len]['comment_id'];

              // 数据加载完毕
              this.sw = true;
            }

            // 是否有更多记录
            if (!res.data.comment_list || res.data.comment_list.length < this.pageSize) {
              this.downFlag = false;
              //如果第一页就加载完毕，则不显示文字
              if (ori_last_id == 0) {
                this.bottomText = "";
              } else {
                this.bottomText = "您太勤奋了，没有更多了";
              }

            } else {
              this.downFlag = true;
              this.bottomText = "加载中";
            }
          }
        });
      },
      postFollow() {
        // 是否关注大V
        this.$parent.login(4).then((res) => {
          let follow_type = !this.isFollow + 0;
          util.ajax.post('/author/follow', util.jsonStringify({
            'author_id': this.author_id,
            'follow_type': follow_type
          })).then((res) => {
            if (res.code == 1) {
              // 切换关注状态
              this.isFollow = follow_type;
            }
          });
        });
      },
      postLike(action) {
        // action 1:收藏，2:点赞
        // next_status 0代表取消 1代表点赞/收藏
        let next_status =
          action == 2 ?
            !this.isLike + 0 :
            !this.isCollect + 0;
        // 先验证是否登录, 收藏传参
        this.$parent.login(3).then((res) => {
          util.ajax.post('/view/change_action_status', util.jsonStringify({
            'view_id': this.view_id,
            'action': action,
            'status': next_status
          })).then((res) => {
            if (res.code == 1) {
              // 更新状态 点赞不需要验证登录
              if (action == 2) {
                if (!next_status) {
                  this.isLike = 0;
                  this.likeAmount -= 1
                } else {
                  this.isLike = 1;
                  this.likeAmount += 1;
                }
              } else if (action == 1) {
                // 全局toast 是收藏 并且 已经登录
                if (!next_status) {
                  this.isCollect = 0;
                  this.$toast('取消收藏', {
                    duration: '1000'
                  });
                } else {
                  this.isCollect = 1;
                  this.$toast('收藏成功', {
                    duration: '1000'
                  });
                }
              }
            }
          });
        });
      },
      showReplayInput(index) {
        let _data = this.commendList.comment_list[index];
        _data.showReplay = !_data.showReplay;
        // this.commendList.comment_list[index].showReplay = !_data[index].showReplay;
        this.$set(this.commendList.comment_list, index, _data);
      },
      postCommentReply(commentid, index, commendContent) {
        if ((commendContent || '').trim().length === 0) {
          this.$toast('回复内容不能为空', {
            duration: '2000'
          });
          return;
        }
        // 回复评论 验证是否登录
        this.$parent.login(2).then((res) => {
          let name = res.data.user_name
          util.ajax.post('/comment/replay', util.jsonStringify({
            'comment_id': commentid,
            'content': commendContent
          })).then((res) => {
            if (res.code == 1) {
              // 判断是否登录
              let commentIndex = this.commendList.comment_list.findIndex(function (item) {
                return item.comment_id == commentid;
              });
              this.commendList.comment_list[commentIndex].reply.push({'user_name': name, content: commendContent});
              //对评论总数+1
              //this.commendList.total_count+=1;
              let _data = this.commendList.comment_list[index];
              _data.showReplay = false;
              this.$set(this.commendList.comment_list, index, _data);
              this.commendList.comment_list[index]['userReplay'] = '';

              return;
            }
          });
        });
      },
      postCommentLike(commentid, isLike) {
        // 是否点赞评论 0:取消，1:点赞
        let that = this;
        //需要校验登录
        this.$parent.login().then((res) => {

          let comment_type = 0;
          isLike ? comment_type = 0 : comment_type = 1;
          util.ajax.post('/comment/like', util.jsonStringify({
            'comment_id': commentid,
            'comment_type': comment_type
          })).then((res) => {
            if (res.code == 1) {
              let commentIndex = that.commendList.comment_list.findIndex(function (item) {
                return item.comment_id == commentid;
              });
              isLike ? that.commendList.comment_list[commentIndex].is_like = false : that.commendList.comment_list[commentIndex].is_like = true;
              isLike ? that.commendList.comment_list[commentIndex].like_amount-- : that.commendList.comment_list[commentIndex].like_amount++;
            }
          });

        });
      },
      authFollowStatus() {
        // 获取初始化关注状态
        util.ajax.get('/author/follow_status?author_id=' + this.author_id).then((res) => {
          if (res.code == 1) {
            this.isFollow = res.data + 0; // bool 转换成0/1
          }
        });
      },
      fetchActionStatus() {
        // 获取初始化观点收藏/点赞状态
        util.ajax.get(`/view/action_status?view_ids=${this.view_id}`).then((res) => {
          if (res.code == 1) {
            this.isLike = res.data[0].like + 0;
            this.isCollect = res.data[0].collect + 0;
          }
        });
      },
      goLargeVipDetail() {
        this.$router.push({path: "/pages/LargeVipDetail", query: {aId: this.author_id}});
      },
      goComment() {
        this.$parent.login().then((res) => {
          this.$router.push({path: "/pages/Comment", query: {id: this.view_id}});
        });
      },
      goDetail(view_id) {
        this.$router.push({path: '/pages/Detail', query: {id: view_id}});
      },
      openShareList() {
        this.isShareListMask = 'block';
      },
      pageAndButtonCount(param) {
        util.ajax.post('/stat/pageAndButton', util.jsonStringify(param)).then(res => {
          /*todu*/
        });
      },
      openShareMask(index) {
        // 分享自己写
        let param = {
          action_type: 2,
          button_type: 19,
          extra: this.view_id || ''
        }
        // 动态传参
        if (index == 0) {
        } else if (index == 1) {
          param.button_type = 20
        } else if (index == 2) {
          param.button_type = 21
        } else if (index == 3) {
          param.button_type = 22
        }
        this.pageAndButtonCount(param)
        if (index <= 3) {
          this.isblock = 'block'
        }

      },
      hideShareMask() {
        this.isblock = 'none';
      },
      hideShareMaskList() {
        this.isShareListMask = 'none';
      },
      goBack() {
        if (window.history.length > 2) {
          this.$router.back();
        } else {
          //直接从文章详情页进来，没有上一页
          this.$router.push({name: 'Index'});
        }
      }

    },
    deactivated() {
      // window.removeEventListener('scroll', this.onScrollPull);
    },

  }
</script>
<style scoped>
  .header-info_btn_liked {
    width: 72px;
    height: 28px;
    line-height: 28px;
    border: 1px solid #FF4E00;
    border-radius: 4px;
    background: #FF4E00;
  }

  .header-info_btn_liked a {
    display: block;
    font-size: .4rem;
    color: white;
    text-align: center;
  }

  .vf-detail_container__good .selected svg {
    color: #fff !important;
    background: #FF4E00 !important;
  }

  .vf-detail_container__good .selected {
    color: #fff !important;
    background: #FF4E00 !important;
  }

  .selected {
    color: #FF4E00 !important;
  }

  .mask-share {
    z-index: 10;
  }

  /*@media only screen and (width: 375px) and (height: 690px){
    .body-layout {
    	padding-bottom: 0.906666rem;
        background: blue;
    }
    .detail-footer{
    	bottom: 0.906666rem !important;
    }
}*/
</style>
